package cn.vin.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

public class HttpClientUtils {
    public static void main(String[] args) throws Exception {
//        test("https://wx.qlogo.cn/mmopen/vi_32/o7RpnhFvZBL7blQGzcFoF7ILyrR4HeOBp65tvJzFL8bgtZbZjtE08vODv7ibWsxbI6J2ZfJ9bTjmXX7jAkOjMGg/132");
//        test("https://wx.qlogo.cn/mmopen/vi_32/C6ylc5V4LCCqloV98QlicDxNJzEe51l6fqzlJNGJEK27aKnFccS5f79X1EAYjIGicg5M9WoOqHxCjmqRMValnuAw/132");
//        test("http://14.215.177.38/");
        /*test("https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLbbXViaLLFrKjQ6NsbNN4psz51tn4ThsLCHQKFaCLJseWO3vsBuwicApsTWSaOdOib0DLI7EhmFFicsQ/132");
        System.out.println("开始比较");
        int size = b1.length;
        for(int i=0; i<size;i++) {
            if (b1[i] != b2[i]) {
                System.out.print(b1[i] + "   " + b2[i]);
                System.out.println(i);
            }
        }*/
        URL url = new URL("http://14.215.177.38/");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        int code = urlConnection.getResponseCode();
        urlConnection.disconnect();
    }
//    static CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(new H).build();
    static byte[] b1;
    static byte[] b2;
    static int i = 1;
    static void test(String urlStr) throws IOException {
        CloseableHttpClient httpclient = createHttpClient(null, 1);
        HttpGet httpGet = new HttpGet(urlStr);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(5000).build();
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            httpGet.setURI(new URI("http://14.215.177.38/"));
//            httpGet.setURI(new URI("http://220.181.38.149/"));
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println("得到的结果:" + response.getStatusLine());//得到请求结果
        HttpEntity entity = response.getEntity();//得到请求回来的数据
        byte[] bytes = EntityUtils.toByteArray(entity);
//        CloseableHttpResponse response2 = httpclient.execute(httpGet);
        if(i == 1) {
            b1 = bytes;
           i++;
        }else {
            b2=bytes;
        }
        System.out.println(bytes.length);
        for(int i=1000; i<2000;i++) {
            System.out.print(bytes[i]);
            System.out.print(",");
        }
        System.out.println();

//        CloseableHttpResponse response3 = httpclient.execute(httpGet);
        response.close();

    }

    public static CloseableHttpClient createHttpClient(String host, int port){
        ConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", plainSocketFactory)
                .register("https", sslSocketFactory).build();

        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
        //设置连接参数
        manager.setMaxTotal(1); // 最大连接数
        manager.setDefaultMaxPerRoute(1); // 路由最大连接数

//        HttpHost httpHost = new HttpHost(host, port);
//        manager.setMaxPerRoute(new HttpRoute(httpHost), 1);

        //请求失败时,进行请求重试
       /* HttpRequestRetryHandler handler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                if (i > 3){
                    //重试超过3次,放弃请求
                    logger.error("retry has more than 3 time, give up request");
                    return false;
                }
                if (e instanceof NoHttpResponseException){
                    //服务器没有响应,可能是服务器断开了连接,应该重试
                    logger.error("receive no response from server, retry");
                    return true;
                }
                if (e instanceof SSLHandshakeException){
                    // SSL握手异常
                    logger.error("SSL hand shake exception");
                    return false;
                }
                if (e instanceof InterruptedIOException){
                    //超时
                    logger.error("InterruptedIOException");
                    return false;
                }
                if (e instanceof UnknownHostException){
                    // 服务器不可达
                    logger.error("server host unknown");
                    return false;
                }
                if (e instanceof ConnectTimeoutException){
                    // 连接超时
                    logger.error("Connection Time out");
                    return false;
                }
                if (e instanceof SSLException){
                    logger.error("SSLException");
                    return false;
                }

                HttpClientContext context = HttpClientContext.adapt(httpContext);
                HttpRequest request = context.getRequest();
                if (!(request instanceof HttpEntityEnclosingRequest)){
                    //如果请求不是关闭连接的请求
                    return true;
                }
                return false;
            }
        };*/

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();
        return client;
    }
}
